package com.zx.kitchen.index.common.utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.zx.kitchen.index.R;
import com.zx.kitchen.index.common.base.Contants;
import com.zx.kitchen.index.common.entity.Messages;
import com.zx.kitchen.index.common.mvp.OnResultListener;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

import cz.msebera.android.httpclient.Header;

/**
 * Http请求的工具类
 */
public class HttpUtils {
    private static final String TAG = "HttpUtils";
    public static final String STATUS_NETWORK = "network_available";
    private static AsyncHttpClient client = new AsyncHttpClient();

    static {
        client.setTimeout(11000);
    }

    public static void get(String urlString, AsyncHttpResponseHandler res) {
        client.get(urlString, res);
    }

    public static void get(String urlString, RequestParams params,
                           AsyncHttpResponseHandler res) {
        client.get(urlString, params, res);
    }

    public static void get(String urlString, JsonHttpResponseHandler res)

    {
        client.get(urlString, res);
    }

    public static void get(String urlString, RequestParams params,
                           JsonHttpResponseHandler res)

    {
        client.get(urlString, params, res);
    }

    public static void get(String uString, BinaryHttpResponseHandler bHandler)

    {
        client.get(uString, bHandler);
    }

    /**
     * 网络交互，
     *
     * @param context
     * @param urlString
     * @param params
     * @param listener
     */
    public static void post(Context context, String urlString, RequestParams params,
                            OnResultListener listener) {
        post(context, urlString, params, 0, listener, null);
    }

    /**
     * 网络交互，
     *
     * @param context
     * @param urlString
     * @param params
     * @param listener
     */
    public static void post(Context context, String urlString, RequestParams params,
                            OnResultListener listener, ProgressDialog progressDialog) {
        post(context, urlString, params, 0, listener, progressDialog);
    }

    /**
     * 网络交互，
     *
     * @param context
     * @param urlString
     * @param params
     * @param listener
     */
    public static void post(Context context, String urlString, RequestParams params,
                            int resquestCode, OnResultListener listener) {
        post(context, urlString, params, resquestCode, listener, null);
    }

    public static void post(Context context, String urlString, RequestParams params,
                            final int resquestCode, final OnResultListener listener, final ProgressDialog progressDialog) {
        post(context, urlString, params,
                resquestCode, listener, progressDialog, null);
    }

    /**
     * 网络交互，有progressDialog
     *
     * @param context
     * @param urlString
     * @param params
     * @param listener
     */
    public static void post(final Context context, String urlString, RequestParams params,
                            final int resquestCode, final OnResultListener listener, final ProgressDialog progressDialog, final View view) {

        if (!NetUtils.isConnected(context)) {
            if (progressDialog != null) {
                if (progressDialog.isShowing())
                    progressDialog.dismiss();
            }
            if (view != null) {
                view.setEnabled(true);
            }
            Toasts.show(context, Contants.getString(context, R.string.net_error), 1000);
            listener.onFailure(resquestCode, Contants.getString(context, R.string.net_error));
            return;
        }
        Log.e(TAG, "post: " + urlString + "?" + params.toString());
        if (view != null) {
            view.setEnabled(false);
        }
        if (progressDialog != null)
            progressDialog.show();
        client.post(urlString, params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {

                if (view != null) {
                    view.setEnabled(true);
                }
                if (progressDialog != null) {
                    if (progressDialog.isShowing())
                        progressDialog.dismiss();
                }
                if (s != null) {
                    Log.e(TAG, "onFailure: " + s);
                }
                listener.onFailure(resquestCode, "" + "加载失败≡(▔﹏▔)≡");
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {

                if (progressDialog != null) {
                    if (progressDialog.isShowing())
                        progressDialog.dismiss();
                }
                if (view != null) {
                    view.setEnabled(true);
                }
                s = s.substring(s.indexOf("{"));
                Log.e(TAG, "onSuccess: " + s);
                Messages messages = JsonUtils.getMessages(s);
                if (messages.getCode() == 1) {
                    listener.onSuccess(resquestCode, JsonUtils.JsonParse(messages));
                } else if (messages.getCode() == 0) {
                    listener.onFailure(resquestCode, "加载失败≡(▔﹏▔)≡");
                }
            }
        });

    }


    public static void calcle(Context context) {
        client.cancelRequests(context, true);
    }

    private static boolean isSuccess = false;

    /**
     * 异步上传文件
     *
     * @param path :文件路径
     * @param url  :上传的url
     */
    public static boolean uploadFile(final Context context, String path, String url, String filename,
                                     final ProgressDialog progress) throws Exception {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ce.docx");
        if (file.exists()) {
            AsyncHttpClient client = new AsyncHttpClient();
            RequestParams params = new RequestParams();
            params.put("uploadFile", file);
            params.put("name", filename);

            // 设置进度条最大值
            progress.setMax(Integer.parseInt(file.length() + ""));

            // 上传文件
            client.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    // 上传成功后要做的工作
                    progress.dismiss();
                    Toast.makeText(context, "上传成功", Toast.LENGTH_LONG).show();
                    // progress.setProgress(0);
                    isSuccess = true;
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    progress.dismiss();
                    Toast.makeText(context, "上传失败", Toast.LENGTH_LONG).show();
                    isSuccess = false;
                }

                @Override
                public void onProgress(long bytesWritten, long totalSize) {
                    int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
                    // 上传进度显示
                    progress.setProgress(count);
                    super.onProgress(bytesWritten, totalSize);
                }

                @Override
                public void onRetry(int retryNo) {
                    super.onRetry(retryNo);
                    // 返回重试次数
                }
            });

        } else {
            progress.dismiss();
            Toast.makeText(context, "文件不存在", Toast.LENGTH_LONG).show();
        }
        return isSuccess;

    }

    /**
     * @param path 要上传的文件路径
     * @param url  服务端接收URL
     * @throws Exception
     */
    public static void uploadFileAll(final Context context, String paramsKey, String path,
                                     String paramsKey1, String path1, String url, Map<String, String> map, Map<String, Integer> map2,
                                     final OnResultListener listener, final ProgressDialog progress) throws Exception {
        File file = new File(path);
//        File file1 = new File(path1);
        if ((file.exists() && file.length() > 0) || (file.exists() && file.length() > 0)) {
            AsyncHttpClient client = new AsyncHttpClient();
            RequestParams params = new RequestParams();

            try {
                params.put(paramsKey, file);
//                params.put(paramsKey1, file1);

                for (Map.Entry<String, String> paramsMap : map.entrySet()) {
                    params.put(paramsMap.getKey(), paramsMap.getValue());
                }
                for (Map.Entry<String, Integer> paramsMap : map2.entrySet()) {
                    params.put(paramsMap.getKey(), paramsMap.getValue());
                }
                Log.e(TAG, "post: " + url + "?" + params.toString());
                // 上传文件
                client.post(url, params, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int i, Header[] headers, byte[] bytes) {
                        String s = new String(bytes);
                        s = s.substring(s.indexOf("{"));
                        Log.e(TAG, "onSuccess: " + s);
                        Messages messages = JsonUtils.getMessages(s);
                        if (messages.getCode() == 1) {
                            listener.onSuccess(1, String.valueOf(messages.getCode()));
                        } else if (messages.getCode() == 0) {
                            listener.onFailure(1, String.valueOf(messages.getCode()));
                        }
                    }

                    @Override
                    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                        Log.e(TAG, "onFailure: ==" + new String(bytes));
                        String s = new String(bytes);
                        s = s.substring(s.indexOf("{"));
                        Log.e(TAG, "onSuccess: " + s);
                        Messages messages = JsonUtils.getMessages(s);
                        if (messages.getCode() == 1) {
                            listener.onSuccess(1, String.valueOf(messages.getCode()));
                        } else if (messages.getCode() == 0) {
                            listener.onFailure(1, String.valueOf(messages.getCode()));
                        }
                    }

                    @Override
                    public void onProgress(long bytesWritten, long totalSize) {
                        int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
                        // 上传进度显示
                        Log.e(TAG, "onProgress: " + count);
                        super.onProgress(bytesWritten, totalSize);
                    }

                    @Override
                    public void onRetry(int retryNo) {
                        super.onRetry(retryNo);
                        Log.e(TAG, "onRetry: " + retryNo);
                        // 返回重试次数
                    }
                });
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        } else {
            Toast.makeText(context, "文件不存在", Toast.LENGTH_LONG).show();
        }
    }

//    /**
//     * @param path 要上传的文件路径
//     * @param url  服务端接收URL
//     * @throws Exception
//     */
//    public static void uploadFile(String path, String url, Context context) {
//        File file = new File(path);
//        if (file.exists() && file.length() > 0) {
//            AsyncHttpClient client = new AsyncHttpClient();
//            RequestParams params = new RequestParams();
//            try {
//                params.put("logo", file);
//                params.put("companyaddress", "aaaa22222aaa");
//                params.put("activity", "aaa");
//                params.put("companytel", "18333333333");
//                params.put("name", "stone");
//                params.put("mobile", "18333333333");
//                params.put("user_data", PreferenceUtil.getStringData(context, Contants.spToken));
//                params.put("activity_print", 1);
//                params.put("day_hour", 5);
//                params.put("month_day", 5);
//
//                // 上传文件AsyncHttpResponseHandler
//                client.post(url, params, new AsyncHttpResponseHandler() {
//                    @Override
//                    public void onSuccess(int i, Header[] headers, byte[] bytes) {
//                        Log.e(TAG, "onSuccess: ===" + new String(bytes));
//                    }
//
//                    @Override
//                    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
//                        Log.e(TAG, "onFailure: " + new String(bytes));
//                    }
//
//                    @Override
//                    public void onProgress(long bytesWritten, long totalSize) {
//                        int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
//                        // 上传进度显示
//                        Log.e(TAG, "onProgress: " + count);
//                        super.onProgress(bytesWritten, totalSize);
//                    }
//
//                    @Override
//                    public void onRetry(int retryNo) {
//                        super.onRetry(retryNo);
//                        Log.e(TAG, "onRetry: " + retryNo);
//                        // 返回重试次数
//                    }
//                });
//
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }
//
//        } else {
//            Log.e(TAG, "文件不存在 ");
//        }
//    }

}
